package org.budo.poi.docx;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.budo.poi.AbstractWorkbook;

/**
 * @author lmw
 * @see https://www.cnblogs.com/sun-flower1314/p/10128796.html
 */
public class DocxWorkbook extends AbstractWorkbook {
    @Override
    public Sheet createSheet(String sheetname) {
        DocxSheet sheet = new DocxSheet(sheetname);
        this.getSheets().put(sheetname, sheet);
        return sheet;
    }

    @Override
    public void write(OutputStream outputStream) throws IOException {
        Sheet sheet = this.getSheetAt(0);
        XWPFDocument document = new XWPFDocument();

        this.writeSheet_1(sheet, document);

        document.write(outputStream);
    }

    private void writeSheet_1(Sheet sheet, XWPFDocument document) {
        int firstRow = sheet.getFirstRowNum();
        int lastRow = sheet.getLastRowNum();

        short firstCell = sheet.getRow(0).getFirstCellNum();
        short lastCell = sheet.getRow(0).getLastCellNum();

        XWPFTable xwpfTable = document.createTable(lastRow, lastCell + 1);
        for (int i = firstRow; i < lastRow; i++) {
            for (int j = firstCell; j <= lastCell; j++) {
                String cellValue = sheet.getRow(i).getCell(j).getStringCellValue();
                XWPFTableCell xwpfTableCell = xwpfTable.getRow(i).getCell(j);

                xwpfTableCell.setText(cellValue);
            }
        }
    }
}